using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using ShopPowerTemplate.Entities;
using ShopPowerTemplate.IoC;
using ShopPowerTemplate.Presentation.Mvc.Extensions;
using ShopPowerTemplate.Presentation.Mvc.Models;
using ShopPowerTemplate.Presentation.Mvc.ViewModels;
using ShopPowerTemplate.Services;

namespace ShopPowerTemplate.Presentation.Mvc.Controllers
{
	public partial class OptionTypeControllerBase : BaseController
	{
		#region Members

        protected IOptionTypeService _optionTypeService;
        protected IOptionService _optionService;

        #endregion

        #region Constructors

        public OptionTypeControllerBase(IOptionTypeService optionTypeService, IOptionService optionService)
        {
            _optionTypeService = optionTypeService;
            _optionService = optionService;
        }	

        #endregion

		#region Index

		// **************************************
        // URL: /OptionType
        // **************************************
		public virtual ActionResult Index()
		{
			IndexOptionTypeViewModel viewModel = new IndexOptionTypeViewModel();
			ViewBag.PageIndex = this.GetPageIndex();
            ViewBag.PageSize = this.GetPageSize();
			ViewBag.SearchValue = this.GetSearchValue();
		
			return View(viewModel);
		}

		[AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult Load(string sidx, string sord, int page, int rows, string search, int mode = 1)
        {
            string searchValue = this.GetSearchValue();
            OrderBy orderBy = this.GetOrderBy();
            int pageIndex = this.GetPageIndex();
            int pageSize = this.GetPageSize();

            if (mode == (int)JQGridActionEnum.DefaultLoad)
            {                
                pageSize = (pageIndex + 1) * pageSize;
                pageIndex = 0;
            }
            else if (mode == (int)JQGridActionEnum.ShowMoreResults)
            {
                pageIndex = page;
                this.SetPageIndex(pageIndex);
            }
            else if (mode == (int)JQGridActionEnum.CustomSearch)
            {
                searchValue = search;
                this.SetSearchValue(searchValue);
                pageIndex = 0;
                this.SetPageIndex(pageIndex);
                orderBy = new OrderBy("", true);
                this.SetOrderBy(orderBy);
            }

            if (!string.IsNullOrEmpty(sidx)) // Sort request
            {
                orderBy = new OrderBy(sidx, sord == "asc");
                this.SetOrderBy(orderBy);
            }

            List<OptionType> searchList = _optionTypeService.Search(searchValue, orderBy.Property, orderBy.Ascending, pageIndex, pageSize);
            int count = _optionTypeService.SearchCount(searchValue);
            
			if (!string.IsNullOrEmpty(sidx)) // Sort request
            {
                pageIndex = this.GetPageIndex();
            }

            var data = new
            {
                total = Math.Ceiling((float)count/(float)pageSize),        // Total pages
                page = pageIndex,      // Current page
                records = count,  // Total records
                rows = from optionType in searchList     // Row data
                       select new
                       {
                           id = optionType.Id,                
                           cell = new string[] {
						   
                                optionType.Name,
								optionType.Description
								
                           }
                       }
            };

            return Json(data);
        }

		[AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult Delete(int id)
        {
            try
            {
                _optionTypeService.Remove(id);
            }
            catch (RemoveException ex)
            {
                Response.StatusCode = 500;
                return Content(ex.Message);
            }
            return Content(string.Empty);
        }
		
		public virtual FileContentResult Report()
        {
            IList<OptionType> _optionTypeList = _optionTypeService.Search(this.GetSearchValue());            
            StringBuilder strBuilder = new StringBuilder();

            // columns
            strBuilder.AppendLine("Name;Description");

            // rows
            foreach (OptionType optionType in _optionTypeList)
            {
                List<string> rowData = new List<string>() { optionType.Name, optionType.Description };
                strBuilder.AppendLine(rowData.Aggregate((x, y) => x + ";" + y));
            }

			// encode report content
            System.IO.MemoryStream content = new System.IO.MemoryStream();
            using (System.IO.StreamWriter writer = new System.IO.StreamWriter(content, UTF8Encoding.UTF8))
                writer.Write(strBuilder.ToString());

            return File(content.ToArray(), "text/csv", "OptionType.csv");
        }
		

		#endregion

		#region Create

		// *******************************************
        // URL: /OptionType/Create
        // *******************************************
		[AcceptVerbs(HttpVerbs.Get)]
        public virtual ActionResult Create()
        {
            OptionType optionType = new OptionType();
            CreateOptionTypeViewModel viewModel = Mapper.Map<OptionType, CreateOptionTypeViewModel>(optionType);
            
			return View(viewModel);
        }

		[AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult Create(CreateOptionTypeViewModel optionTypeModel)
        {
            if (ModelState.IsValid)
            {
                OptionType optionType = new OptionType();
                AutoMapper.Mapper.Map<CreateOptionTypeViewModel, OptionType>(optionTypeModel, optionType);
 

				_optionTypeService.Add(optionType);

                return RedirectToAction("Edit", new { id = optionType.Id});
            }
            else
            {

                return View(optionTypeModel);
            }
		}
		

		#endregion

		#region Edit

		// *******************************************
        // URL: /OptionType/Edit/id
        // *******************************************
		[AcceptVerbs(HttpVerbs.Get)]
        public virtual ActionResult Edit(int id)
        {
            OptionType optionType = _optionTypeService.Find(id);
            EditOptionTypeViewModel viewModel = Mapper.Map<OptionType, EditOptionTypeViewModel>(optionType);
            
			return View(viewModel);
        }

		[AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult Edit(EditOptionTypeViewModel optionTypeModel)
        {
            if (ModelState.IsValid)
            {
                OptionType optionType = _optionTypeService.Find(optionTypeModel.Id);
                AutoMapper.Mapper.Map<EditOptionTypeViewModel, OptionType>(optionTypeModel, optionType);
                
				_optionTypeService.Change(optionType);

                return RedirectToAction("Index");
            }
            else
            {

                return View(optionTypeModel);
            }
		}
		[AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult LoadOptions(string sidx, string sord, int page, int rows, string search, int mode = 1, int masterId = 0)
        {
			OptionType currentOptionType = _optionTypeService.Find(masterId);
            List<Option> list = currentOptionType.Options.ToList();
			int count = list.Count();

			var data = new
            {
                total = 1,        // Total pages
                page = 1,      // Current page
                records = count,  // Total records
                rows = from option in list     // Row data
                       select new
                       {
                           id = option.Id,                
                           cell = new string[] {
                                option.Name,
								option.Description
                           }
                       }
            };

            // Return elements
            return Json(data);
        }

		public virtual ActionResult AddOptions(int masterId = 0)
        {
            PopUpOptionViewModel viewModel = new PopUpOptionViewModel();

			viewModel.OptionTypeId = masterId;
			ViewBag.MasterProperty = "OptionType";
            ViewBag.Name = "AddOptions";

            return PartialView("~/Views/Option/PopUp.cshtml", viewModel);
        }
		
		[AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult AddOptions(PopUpOptionViewModel optionModel)
        {
            if (ModelState.IsValid)
            {
                Option options = new Option();
                AutoMapper.Mapper.Map<PopUpOptionViewModel, Option>(optionModel, options);

				OptionType optionType = _optionTypeService.Find(options.OptionType.Id);
				_optionTypeService.AddOptions(optionType, options);
                
				Response.StatusCode = 200;
                return Content("OK", "text/plain");
            }
            else
            {
				ViewBag.MasterProperty = "OptionType";
            	ViewBag.Name = "AddOptions";


				return PartialView("~/Views/Option/PopUp.cshtml", optionModel);
            }
        }	
		
		public virtual ActionResult EditOptions(int id, int masterId = 0)
        {
			Option option = _optionService.Find(id);
            PopUpOptionViewModel viewModel = Mapper.Map<Option, PopUpOptionViewModel>(option);

			List<OptionType> allOptionType = _optionTypeService.FindAll();
			viewModel.OptionTypeId = masterId;
			ViewBag.MasterProperty = "OptionType";
            ViewBag.Name = "EditOptions";

            return PartialView("~/Views/Option/PopUp.cshtml", viewModel);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult EditOptions(PopUpOptionViewModel optionModel)
        {
            if (ModelState.IsValid)
            {
                Option option = _optionService.Find(optionModel.Id);
                AutoMapper.Mapper.Map<PopUpOptionViewModel, Option>(optionModel, option);

                _optionService.Change(option);

                Response.StatusCode = 200;
                return Content("OK", "text/plain");
            }
            else
            {
				List<OptionType> allOptionType = _optionTypeService.FindAll();
				optionModel.OptionTypeList = allOptionType;
				ViewBag.MasterProperty = "OptionType";

                return PartialView("~/Views/Option/PopUp.cshtml", optionModel);
            }
        }
		
		[AcceptVerbs(HttpVerbs.Post)]
        public virtual void DeleteOptions(int id, int masterId = 0)
        {
			Option option = _optionService.Find(id);
			OptionType currentOptionType = _optionTypeService.Find(masterId);

            _optionTypeService.RemoveOptions(currentOptionType, option);
        }
			
		public virtual FileContentResult ReportOptions(int masterId = 0)
        {
			OptionType currentOptionType = _optionTypeService.Find(masterId);
            IList<Option> _optionsList = currentOptionType.Options.ToList();          
            StringBuilder strBuilder = new StringBuilder();

            // columns
            strBuilder.AppendLine("Name;Description");

            // rows
            foreach (Option option in _optionsList)
            {
                List<string> rowData = new List<string>() { option.Name, option.Description };
                strBuilder.AppendLine(rowData.Aggregate((x, y) => x + ";" + y));
            }

			// encode report content
            System.IO.MemoryStream content = new System.IO.MemoryStream();
            using (System.IO.StreamWriter writer = new System.IO.StreamWriter(content, UTF8Encoding.UTF8))
                writer.Write(strBuilder.ToString());

            return File(content.ToArray(), "text/csv", "Options.csv");
        }
		

		#endregion

		#region Details

		// *******************************************
        // URL: /OptionType/Details/id
        // *******************************************
		[AcceptVerbs(HttpVerbs.Get)]
        public virtual ActionResult Details(int id)
        {
            OptionType optionType = _optionTypeService.Find(id);
            DetailsOptionTypeViewModel viewModel = Mapper.Map<OptionType, DetailsOptionTypeViewModel>(optionType);
            
			return View(viewModel);
        }
		

		#endregion
	}
}
